<template>
  <div class="note-chart-card">
    <div class="note-chart-title">随笔 总:{{ totalNotes }}篇</div>
    <div class="note-chart" ref="chartRef" style="width: 100%; height: 220px;"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
let chartInstance = null

// 生成最近7天的日期
function getLast7Days() {
  const arr = [];
  const today = new Date();
  for (let i = 6; i >= 0; i--) {
    const d = new Date(today);
    d.setDate(today.getDate() - i);
    arr.push(d.toISOString().slice(0, 10));
  }
  return arr;
}
const dateArr = getLast7Days();

// 示例数据：7天内有多天有随笔，数据范围1~5
const noteData = [1, 2, 0, 3, 0, 4, 5];
const totalNotes = noteData.filter(n => n > 0).reduce((sum, n) => sum + n, 0);

const option = {
  tooltip: {
    trigger: 'axis',
    backgroundColor: '#fff',
    borderColor: '#ccc',
    borderWidth: 1,
    textStyle: { color: '#333' },
    axisPointer: { type: 'shadow' },
    formatter: params => {
      let item = params[0];
      return `${item.axisValue}<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background:${item.color}"></span>随笔: ${item.data}`;
    }
  },
  grid: {
    left: 40,
    right: 20,
    top: 30,
    bottom: 60
  },
  xAxis: {
    type: 'category',
    data: dateArr,
    axisLabel: {
      interval: 0,
      rotate: 35
    }
  },
  yAxis: {
    type: 'value',
    min: 1,
    max: 5,
    interval: 1
  },
  series: [
    {
      name: '随笔',
      type: 'bar',
      data: noteData,
      barWidth: 20,
      itemStyle: {
        color: '#3DD4FF'
      }
    }
  ]
}

onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(option)
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (chartInstance) chartInstance.dispose()
})

function resizeChart() {
  if (chartInstance) chartInstance.resize()
}
</script>

<style scoped>
.note-chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 10px 10px 0 10px;
}
.note-chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #888;
  margin-bottom: 0;
  margin-left: 5px;
}
.note-chart {
  width: 100%;
  height: 220px;
}
</style>
